package com.imooc.util;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.Entity;
import javax.persistence.ManyToOne;

import net.sf.json.JSONObject;

import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.imooc.menu.Button;
import com.imooc.menu.ClickButton;
import com.imooc.menu.Menu;
import com.imooc.menu.ViewButton;
import com.imooc.po.AccessToken;
import com.imooc.trans.Data;
import com.imooc.trans.Parts;
import com.imooc.trans.Symbols;
import com.imooc.trans.TransResult;
import com.jinzht.tools.Config;

/**
 * ΢�Ź�����
 * 
 * @author Stephen
 *
 */
@Entity
public class WeixinUtil {
	private static final String APPID = "wx75947c6b0be286c2";
	private static final String APPSECRET = "e7a59b7232b7ad34db4bde780386b0ce";

	private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";

	private static final String UPLOAD_URL = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE";

	private static final String CREATE_MENU_URL = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";

	private static final String QUERY_MENU_URL = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token=ACCESS_TOKEN";

	private static final String DELETE_MENU_URL = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=ACCESS_TOKEN";

	/**
	 * get请求
	 * 
	 * @param url
	 * @return
	 * @throws ParseException
	 * @throws IOException
	 * @throws HttpException
	 * @throws URISyntaxException
	 */
	public static JSONObject doGetStr(String url) throws ParseException,
			IOException, HttpException, URISyntaxException {
		DefaultHttpClient client = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(url);
		JSONObject jsonObject = null;
		HttpResponse httpResponse = client.execute(httpGet);
		HttpEntity entity = httpResponse.getEntity();
		if (entity != null) {
			String result = EntityUtils.toString(entity, "UTF-8");
			jsonObject = JSONObject.fromObject(result);
		}
		return jsonObject;
	}

	/**
	 * POST请求
	 * 
	 * @param url
	 * @param outStr
	 * @return
	 * @throws ParseException
	 * @throws IOException
	 * @throws URISyntaxException
	 * @throws HttpException
	 */
	public static JSONObject doPostStr(String url, String outStr)
			throws ParseException, IOException, URISyntaxException,
			HttpException {
		DefaultHttpClient client = new DefaultHttpClient();
		HttpPost httpost = new HttpPost(url);
		JSONObject jsonObject = null;
		httpost.setEntity(new StringEntity(outStr, "UTF-8"));
		HttpResponse response = client.execute(httpost);
		String result = EntityUtils.toString(response.getEntity(), "UTF-8");
		jsonObject = JSONObject.fromObject(result);
		return jsonObject;
	}

	/**
	 * 文件上传
	 * 
	 * @param filePath
	 * @param accessToken
	 * @param type
	 * @return
	 * @throws IOException
	 * @throws NoSuchAlgorithmException
	 * @throws NoSuchProviderException
	 * @throws KeyManagementException
	 */
	public static String upload(String filePath, String accessToken, String type)
			throws IOException, NoSuchAlgorithmException,
			NoSuchProviderException, KeyManagementException {
		File file = new File(filePath);
		if (!file.exists() || !file.isFile()) {
			throw new IOException("文件不存在");
		}

		String url = UPLOAD_URL.replace("ACCESS_TOKEN", accessToken).replace(
				"TYPE", type);

		URL urlObj = new URL(url);
		// 连接
		HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();

		con.setRequestMethod("POST");
		con.setDoInput(true);
		con.setDoOutput(true);
		con.setUseCaches(false);

		// 设置请求头信息
		con.setRequestProperty("Connection", "Keep-Alive");
		con.setRequestProperty("Charset", "UTF-8");

		// 设置边界
		String BOUNDARY = "----------" + System.currentTimeMillis();
		con.setRequestProperty("Content-Type", "multipart/form-data; boundary="
				+ BOUNDARY);

		StringBuilder sb = new StringBuilder();
		sb.append("--");
		sb.append(BOUNDARY);
		sb.append("\r\n");
		sb.append("Content-Disposition: form-data;name=\"file\";filename=\""
				+ file.getName() + "\"\r\n");
		sb.append("Content-Type:application/octet-stream\r\n\r\n");

		byte[] head = sb.toString().getBytes("utf-8");

		// 获得输出流
		OutputStream out = new DataOutputStream(con.getOutputStream());
		// 输出表头
		out.write(head);

		// 文件正文部分
		// 把文件已流文件的方式 推入到url中
		DataInputStream in = new DataInputStream(new FileInputStream(file));
		int bytes = 0;
		byte[] bufferOut = new byte[1024];
		while ((bytes = in.read(bufferOut)) != -1) {
			out.write(bufferOut, 0, bytes);
		}
		in.close();

		// 结尾部分
		byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线

		out.write(foot);

		out.flush();
		out.close();

		StringBuffer buffer = new StringBuffer();
		BufferedReader reader = null;
		String result = null;
		try {
			// 定义BufferedReader输入流来读取URL的响应
			reader = new BufferedReader(new InputStreamReader(
					con.getInputStream()));
			String line = null;
			while ((line = reader.readLine()) != null) {
				buffer.append(line);
			}
			if (result == null) {
				result = buffer.toString();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				reader.close();
			}
		}

		JSONObject jsonObj = JSONObject.fromObject(result);
		System.out.println(jsonObj);
		String typeName = "media_id";
		if (!"image".equals(type)) {
			typeName = type + "_media_id";
		}
		String mediaId = jsonObj.getString(typeName);
		return mediaId;
	}

	/**
	 * 获取accessToken
	 * 
	 * @return
	 * @throws ParseException
	 * @throws IOException
	 * @throws URISyntaxException
	 * @throws HttpException
	 */
	public static AccessToken getAccessToken() throws ParseException,
			IOException, HttpException, URISyntaxException {
		AccessToken token = new AccessToken();
		String url = ACCESS_TOKEN_URL.replace("APPID", APPID).replace(
				"APPSECRET", APPSECRET);
		JSONObject jsonObject = doGetStr(url);
		if (jsonObject != null) {
			token.setToken(jsonObject.getString("access_token"));
			token.setExpiresIn(jsonObject.getInt("expires_in"));
		}
		return token;
	}

	/**
	 * 组装菜单
	 * 
	 * @return
	 */
	public static Menu initMenu() {
		Menu menu = new Menu();
//		ClickButton button11 = new ClickButton();
//		button11.setName("最新资讯");
//		button11.setType("click");
//		button11.setKey("11");
//
//		ViewButton button21 = new ViewButton();
//		button21.setName("商务合作");
//		button21.setType("view");
//		button21.setUrl("http://www.haoduocheyou.com");
//		
//
//		ClickButton button31 = new ClickButton();
//		button31.setName("我要报名");
//		button31.setType("scancode_push");
//		button31.setKey("31");
//
//		ClickButton button32 = new ClickButton();
//		button32.setName("我的门票");
//		button32.setType("location_select");
//		button32.setKey("32");
//
//		Button button = new Button();
//		button.setName("速度嘉年华");
//		button.setSub_button(new Button[] { button31, button32 });
		//最新资讯
		ViewButton button11 = new ViewButton();
		button11.setName("新闻资讯");
		button11.setType("view");
		button11.setUrl(Config.STRING_SYSTEM_ADDRESS+"wechat/inforNews.action");
		
		ViewButton button12 = new ViewButton();
		button12.setName("项目动态");
		button12.setType("view");
		button12.setUrl(Config.STRING_SYSTEM_ADDRESS+"wechat/inforProject.action");
		
		Button button1 = new Button();
		button1.setName("最新资讯");
		button1.setSub_button(new Button[] {button11, button12 });
		
		//学习资本
		ViewButton button21 = new ViewButton();
		button21.setName("主题活动");
		button21.setType("view");
		button21.setUrl(Config.STRING_SYSTEM_ADDRESS+"wechat/learnSport.action");
		
		ViewButton button22 = new ViewButton();
		button22.setName("课程研修");
		button22.setType("view");
		button22.setUrl(Config.STRING_SYSTEM_ADDRESS+"wechat/learnCourse.action");
		
		ViewButton button23 = new ViewButton();
		button23.setName("项目观摩");
		button23.setType("view");
		button23.setUrl(Config.STRING_SYSTEM_ADDRESS+"wechat/learnProject.action");
		
		ViewButton button24 = new ViewButton();
		button24.setName("报名查询");
		button24.setType("view");
		button24.setUrl(Config.STRING_SYSTEM_ADDRESS+"wechat/learnSearch.action");
		
		Button button2 = new Button();
		button2.setName("学习资本");
		button2.setSub_button(new Button[] {button21, button22,button23,button24 });
				
		//关于我们
		ViewButton button31 = new ViewButton();
		button31.setName("公司介绍");
		button31.setType("view");
		button31.setUrl(Config.STRING_SYSTEM_ADDRESS+"wechat/aboutCompany.action");
		
		ViewButton button32 = new ViewButton();
		button32.setName("成功案例");
		button32.setType("view");
		button32.setUrl(Config.STRING_SYSTEM_ADDRESS+"wechat/aboutSuccess.action");

		ViewButton button33 = new ViewButton();
		button33.setName("联系我们");
		button33.setType("view");
		button33.setUrl(Config.STRING_SYSTEM_ADDRESS+"wechat/aboutTell.action");
		
		ViewButton button34 = new ViewButton();
		button34.setName("诚聘英才");
		button34.setType("view");
		button34.setUrl(Config.STRING_SYSTEM_ADDRESS+"wechat/aboutZhao.action");
		
		Button button3 = new Button();
		button3.setName("最新资讯");
		button3.setSub_button(new Button[] {button31, button32,button33,button34 });
		

		menu.setButton(new Button[] { button1, button2, button3 });
		return menu;
	}

	public static String createMenu(String token, Menu menu)
			throws ParseException, IOException, URISyntaxException,
			HttpException {
		Button[] buttons = menu.getButton();

		// 遍历
		JSONObject menus = new JSONObject();

		List list = new ArrayList();
		for (int i = 0; i < buttons.length; i++) {
			JSONObject m = new JSONObject();

			Object btn = buttons[i];
			// 判断是否有子菜单
			Button button = (Button) btn;
			m.put("type", button.getType());
			m.put("name", button.getName());

			if (btn.getClass() == ViewButton.class) {
				ViewButton vbutton = (ViewButton) btn;
				m.put("url", vbutton.getUrl());
			} else if (btn.getClass() == ClickButton.class) {
				ClickButton cbutton = (ClickButton) btn;
				m.put("key", cbutton.getKey());
			}

			// 子菜单
			if (button.getSub_button() != null
					&& button.getSub_button().length > 0) {
				List l = new ArrayList();
				for (int j = 0; j < button.getSub_button().length; j++) {
					ViewButton b = (ViewButton) button.getSub_button()[j];

					Map mm = new HashMap();
					mm.put("type", b.getType());
					mm.put("name", b.getName());
					mm.put("url", b.getUrl());

					l.add(mm);
				}
				m.put("sub_button", l);
			}

			list.add(m);
		}
		menus.put("button", list);

		ObjectMapper mapper = new ObjectMapper();
		String json = mapper.writeValueAsString(menus);
		
		return json;
	}

	public static int createMenu(String token, String menu)
			throws ParseException, IOException, URISyntaxException,
			HttpException {
		int result = 0;
		String url = CREATE_MENU_URL.replace("ACCESS_TOKEN", token);
		JSONObject jsonObject = doPostStr(url, menu);
		if (jsonObject != null) {
			System.out.println(jsonObject);
			result = jsonObject.getInt("errcode");
		}
		return result;
	}

	public static JSONObject queryMenu(String token) throws ParseException,
			IOException, HttpException, URISyntaxException {
		String url = QUERY_MENU_URL.replace("ACCESS_TOKEN", token);
		JSONObject jsonObject = doGetStr(url);
		return jsonObject;
	}

	public static int deleteMenu(String token) throws ParseException,
			IOException, HttpException, URISyntaxException {
		String url = DELETE_MENU_URL.replace("ACCESS_TOKEN", token);
		JSONObject jsonObject = doGetStr(url);
		int result = 0;
		if (jsonObject != null) {
			result = jsonObject.getInt("errcode");
		}
		return result;
	}

	public static String translate(String source) throws ParseException,
			IOException, HttpException, URISyntaxException {
		String url = "http://openapi.baidu.com/public/2.0/translate/dict/simple?client_id=jNg0LPSBe691Il0CG5MwDupw&q=KEYWORD&from=auto&to=auto";
		url = url.replace("KEYWORD", URLEncoder.encode(source, "UTF-8"));
		JSONObject jsonObject = doGetStr(url);
		String errno = jsonObject.getString("errno");
		Object obj = jsonObject.get("data");
		StringBuffer dst = new StringBuffer();
		if ("0".equals(errno) && !"[]".equals(obj.toString())) {
			TransResult transResult = (TransResult) JSONObject.toBean(
					jsonObject, TransResult.class);
			Data data = transResult.getData();
			Symbols symbols = data.getSymbols()[0];
			String phzh = symbols.getPh_zh() == null ? "" : "中文拼音："
					+ symbols.getPh_zh() + "\n";
			String phen = symbols.getPh_en() == null ? "" : "英式英标："
					+ symbols.getPh_en() + "\n";
			String pham = symbols.getPh_am() == null ? "" : "美式英标："
					+ symbols.getPh_am() + "\n";
			dst.append(phzh + phen + pham);

			Parts[] parts = symbols.getParts();
			String pat = null;
			for (Parts part : parts) {
				pat = (part.getPart() != null && !"".equals(part.getPart())) ? "["
						+ part.getPart() + "]"
						: "";
				String[] means = part.getMeans();
				dst.append(pat);
				for (String mean : means) {
					dst.append(mean + ";");
				}
			}
		} else {
			dst.append(translateFull(source));
		}
		return dst.toString();
	}

	public static String translateFull(String source) throws ParseException,
			IOException, HttpException, URISyntaxException {
		String url = "http://openapi.baidu.com/public/2.0/bmt/translate?client_id=jNg0LPSBe691Il0CG5MwDupw&q=KEYWORD&from=auto&to=auto";
		url = url.replace("KEYWORD", URLEncoder.encode(source, "UTF-8"));
		JSONObject jsonObject = doGetStr(url);
		StringBuffer dst = new StringBuffer();
		List<Map> list = (List<Map>) jsonObject.get("trans_result");
		for (Map map : list) {
			dst.append(map.get("dst"));
		}
		return dst.toString();
	}
}
